<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>中文RAG聊天示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .app-container {
            display: flex;
            gap: 20px;
            height: 80vh;
        }
        .chat-container {
            flex: 2;
            display: flex;
            flex-direction: column;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .document-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .header {
            background-color: #4a90e2;
            color: white;
            padding: 15px;
            font-weight: bold;
        }
        .messages {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
        }
        .input-area {
            display: flex;
            padding: 10px;
            border-top: 1px solid #ddd;
        }
        #message-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: none;
        }
        button {
            background-color: #4a90e2;
            color: white;
            border: none;
            padding: 0 15px;
            margin-left: 10px;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #3a80d2;
        }
        .message {
            margin-bottom: 15px;
            max-width: 80%;
        }
        .user {
            align-self: flex-end;
            background-color: #e1f0fe;
            padding: 10px 15px;
            border-radius: 18px 18px 0 18px;
            margin-left: auto;
        }
        .assistant {
            align-self: flex-start;
            background-color: #f0f0f0;
            padding: 10px 15px;
            border-radius: 18px 18px 18px 0;
            white-space: pre-wrap;
        }
        #file-upload {
            display: none;
        }
        .file-upload-container {
            padding: 15px;
            border-bottom: 1px solid #ddd;
        }
        .documents {
            flex: 1;
            padding: 15px;
            overflow-y: auto;
        }
        .document-item {
            background-color: #f0f0f0;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 4px;
            font-size: 0.9em;
        }
        .sources {
            font-size: 0.8em;
            color: #666;
            margin-top: 5px;
        }
    </style>
</head>
<body>
    <h1>中文RAG聊天示例</h1>
    
    <div class="app-container">
        <div class="chat-container">
            <div class="header">聊天</div>
            <div class="messages" id="messages"></div>
            <div class="input-area">
                <textarea id="message-input" placeholder="输入您的问题..." rows="3"></textarea>
                <button id="send-button">发送</button>
            </div>
        </div>
        
        <div class="document-container">
            <div class="header">文档管理</div>
            <div class="file-upload-container">
                <button id="upload-button">选择文件</button>
                <input type="file" id="file-upload" multiple accept=".txt,.pdf,.md,.docx,.csv">
            </div>
            <div class="documents" id="documents">
                <p>上传文档以增强聊天功能</p>
            </div>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const messagesContainer = document.getElementById('messages');
            const messageInput = document.getElementById('message-input');
            const sendButton = document.getElementById('send-button');
            const fileUpload = document.getElementById('file-upload');
            const uploadButton = document.getElementById('upload-button');
            const documentsContainer = document.getElementById('documents');
            
            // 历史消息
            const messages = [];
            
            // 发送按钮点击事件
            sendButton.addEventListener('click', sendMessage);
            
            // 回车键发送消息
            messageInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            // 上传按钮点击事件
            uploadButton.addEventListener('click', function() {
                fileUpload.click();
            });
            
            // 文件选择事件
            fileUpload.addEventListener('change', uploadFiles);
            
            // 发送消息函数
            async function sendMessage() {
                const content = messageInput.value.trim();
                if (!content) return;
                
                // 添加用户消息到界面
                addMessage('user', content);
                messageInput.value = '';
                
                // 添加消息到历史记录
                messages.push({
                    role: 'user',
                    content: content
                });
                
                try {
                    // 调用API发送消息
                    const response = await fetch('/api/chat', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            messages: messages
                        })
                    });
                    
                    // 创建助手消息元素
                    const assistantMessage = document.createElement('div');
                    assistantMessage.className = 'message assistant';
                    messagesContainer.appendChild(assistantMessage);
                    
                    // 处理流式响应
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let responseText = '';
                    
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;
                        
                        const text = decoder.decode(value);
                        const lines = text.split('\n');
                        
                        for (const line of lines) {
                            if (!line) continue;
                            
                            // 解析数据流
                            const colonIndex = line.indexOf(':');
                            if (colonIndex !== -1) {
                                const content = line.slice(colonIndex + 1);
                                try {
                                    const parsed = JSON.parse(content);
                                    responseText += parsed;
                                    assistantMessage.textContent = responseText;
                                    // 自动滚动到底部
                                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                                } catch (e) {
                                    console.error('解析响应失败:', e);
                                }
                            }
                        }
                    }
                    
                    // 添加助手消息到历史记录
                    messages.push({
                        role: 'assistant',
                        content: responseText
                    });
                    
                } catch (error) {
                    console.error('发送消息失败:', error);
                    addMessage('assistant', '发送消息失败，请重试。');
                }
            }
            
            // 上传文件函数
            async function uploadFiles() {
                const files = fileUpload.files;
                if (!files.length) return;
                
                const formData = new FormData();
                for (const file of files) {
                    formData.append('files', file);
                }
                
                try {
                    const response = await fetch('/api/rag/upload', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    if (result.success) {
                        // 更新文档列表
                        updateDocumentsList();
                        addMessage('assistant', `成功上传 ${result.file_paths.length} 个文件。您现在可以基于这些文档进行提问。`);
                    } else {
                        addMessage('assistant', `文件上传失败: ${result.message}`);
                    }
                } catch (error) {
                    console.error('上传文件失败:', error);
                    addMessage('assistant', '上传文件失败，请重试。');
                }
                
                // 清空文件选择
                fileUpload.value = '';
            }
            
            // 更新文档列表
            async function updateDocumentsList() {
                try {
                    // 这里模拟获取文档列表，实际应用可能需要另一个API端点
                    // 这里我们假设已上传的文档已在RAG系统中
                    documentsContainer.innerHTML = '<p>已上传的文档:</p>';
                    
                    // 添加成功上传的文件提示
                    const docItem = document.createElement('div');
                    docItem.className = 'document-item';
                    docItem.textContent = '文档已成功添加到知识库。';
                    documentsContainer.appendChild(docItem);
                    
                } catch (error) {
                    console.error('获取文档列表失败:', error);
                    documentsContainer.innerHTML = '<p>获取文档列表失败</p>';
                }
            }
            
            // 添加消息到界面
            function addMessage(role, content) {
                const messageElement = document.createElement('div');
                messageElement.className = `message ${role}`;
                messageElement.textContent = content;
                messagesContainer.appendChild(messageElement);
                
                // 自动滚动到底部
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
        });
    </script>
</body>
</html> 